package org.ns.longhttp.selector.datamapper;

import org.ns.longhttp.selector.datamapper.responseid.DataResponseIdService;

import java.util.*;

/**
 * 数据映射的实体
 */
public abstract class DataMappingEntry {

    // ID生成服务
    private DataResponseIdService responseIdService;
    // 映射的KEY
    private String key;

    public DataMappingEntry() { }

    public static DataMappingEntry create(Class<? extends DataMappingEntry> type) {
        try {
            return type.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 数据映射实体
     * @param key
     * @param responseIdService
     */
    public DataMappingEntry(String key, DataResponseIdService responseIdService) {
        init(key, responseIdService);
    }

    public DataMappingEntry init(String key, DataResponseIdService responseIdService) {
        this.key = key;
        this.responseIdService = responseIdService;
        return this;
    }

    /**
     * 添加数据应答实体
     * @param dataResponseEntry
     * @param second  超时时间 "秒"
     */
    public void add(DataResponseEntry dataResponseEntry, int second) {
        long id = responseIdService.getId();
        dataResponseEntry.setId(id);
        put(id, dataResponseEntry, second);
    }

    public abstract void put(long id, DataResponseEntry dataResponseEntry, int second);

    /**
     * 清理失效的数据
     */
    public abstract void clearInvalid();

    /**
     * 获得下一批数据、获得的数据的ID一定比传入的ID大
     * @param id
     * @return
     */
    public abstract List<DataResponseEntry> getDataResponseEntrys(long id) ;

    /**
     * 是否有新的数据
     * @param id
     * @return
     */
    public abstract boolean hasNew(long id) ;

    public long getMaxId() {
        return this.responseIdService.getMaxId();
    }

    public DataResponseIdService getResponseIdService() {
        return responseIdService;
    }

    public String getKey() {
        return key;
    }
}
